{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright (c) MONAI Consortium  \n",
    "Licensed under the Apache License, Version 2.0 (the \"License\");  \n",
    "you may not use this file except in compliance with the License.  \n",
    "You may obtain a copy of the License at  \n",
    "&nbsp;&nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0  \n",
    "Unless required by applicable law or agreed to in writing, software  \n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,  \n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  \n",
    "See the License for the specific language governing permissions and  \n",
    "limitations under the License. \n",
    "\n",
    "# MONAI Label - Lung Nodule Detection - 3D Slicer Integration\n",
    "\n",
    "***The Detection Task Workflow in MONAI Label***\n",
    "\n",
    "In this notebook, we provide a monaibundle app usecase example with lung nodule detection. The first detection task that can be used within MONAI Label.\n",
    "\n",
    "3D Slicer as the client viewer, we show how MONAI Label workflow serves as an interactive AI-Assisted tool for box-based ROI detection labeling.\n",
    "\n",
    "**Lung Nodule Detection Bundle:**\n",
    "\n",
    "![workflow](./figures/monailabel_detection_3dslicer/3dslicer_demo.png)\n",
    "\n",
    "\n",
    "**Method:** Lung Nodule Detection Networks\n",
    "\n",
    "The workflow of lung nodule detection with CT scans is from RetinaNet (Lin, Tsung-Yi, et al. \"Focal loss for dense object detection.\" ICCV 2017. https://arxiv.org/abs/1708.02002).\n",
    "\n",
    "![workflow](./figures/monailabel_detection_3dslicer/detection_networks.png)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup environment\n",
    "\n",
    "MONAI Label is pre-built within the MONAI Toolkit. Download monaibundle app\n",
    "\n",
    "### Prerequisites\n",
    "- **Install MONAI Label**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install monailabel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **Get latest MONAI Label Slicer plugin** (Optional)\n",
    "\n",
    "If you are using older release of 3D Slicer MONAI Label plugin, you can update to the latest plugin which supports ***drawing ROI nodes from MONAI Label server prediction***.\n",
    "\n",
    "Or to use the developer mode of MONAI Label plugin by:\n",
    "\n",
    " - Pull latest MONAI Label repo:\n",
    " ```bash\n",
    " git clone https://github.com/Project-MONAI/MONAILabel.git\n",
    " ```\n",
    " - Go to `MONAILabel/plugins/slicer/`\n",
    " - Follow the Readme page to use developer mode of Slicer plugin.\n",
    " https://github.com/Project-MONAI/MONAILabel/tree/main/plugins/slicer#install-plugin-in-developer-mode\n",
    "    - Install Plugin in Developer Mode\n",
    "        - Open 3D Slicer: Go to Edit -> Application Settings -> Modules -> Additional Module Paths\n",
    "        - Add New Module Path: <FULL_PATH>/plugins/slicer/MONAILabel\n",
    "        - Restart 3D Slicer\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1 Download monaibundle app\n",
    "Sample-app with built-in versions are in the Toolkit, pull the monaibundle app using monailabel API "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using PYTHONPATH=/home/chyang/anaconda3/envs:\n",
      "\n",
      "Directory already exists: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle\n"
     ]
    }
   ],
   "source": [
    "!monailabel apps --download --name monaibundle --output apps"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 Download sample data\n",
    "The lung nodule detection model is trained and evaluated using [LUNA16](https://luna16.grand-challenge.org/Home/) dataset.\n",
    "\n",
    "LUNA16 is a public dataset of CT lung nodule detection. Using raw CT scans, the goal is to identify locations of possible nodules and to assign a probability for being a nodule to each location.\n",
    "\n",
    "Disclaimer: We are not the host of the data. Please make sure to read the requirements and usage policies of the data and give credit to the authors of the dataset! We acknowledge the National Cancer Institute and the Foundation for the National Institutes of Health, and their critical role in the creation of the free publicly available LIDC/IDRI Database used in this study.\n",
    "\n",
    " - If you are going to use full dataset of LUNA16, please refer to the dataset link, download the data, create and preprocess the images following [this page](        https://github.com/Project-MONAI/model-zoo/tree/dev/models/lung_nodule_ct_detection#data \n",
    ").\n",
    " \n",
    " - In this tutorial, we prepared a sample subset, resampled and ready to use. The subset is only for demonstration. Download [here](https://github.com/Project-MONAI/MONAILabel/releases/download/data/detection_dataset.zip).\n",
    " \n",
    "   Or use these commands to download and extract directly.\n",
    "\n",
    "```bash\n",
    "mkdir datasets\n",
    "wget \"https://github.com/Project-MONAI/MONAILabel/releases/download/data/detection_dataset.zip\" -O datasets/detection_dataset.zip\n",
    "unzip datasets/detection_dataset.zip -d datasets/detection_dataset\n",
    "```\n",
    " \n",
    " - The detection model also supports MSD Task06_Lung dataset for inference. Note this dataset is created for nodule segmentation task. We do not use the segmentation mask, only the images for inference. Use following monailabel API to automatically download the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using PYTHONPATH=/home/chyang/anaconda3/envs:\n",
      "\n",
      "Directory already exists: datasets/Task06_Lung\n"
     ]
    }
   ],
   "source": [
    "!monailabel datasets --download --name Task06_Lung --output datasets"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 Starting MONAI Label Server\n",
    "\n",
    "Specify the bundle name in `--conf models <BUNDLENAME>` argument. For example: lung_nodule_ct_detection\n",
    "\n",
    "**Note:** If you are running a MONAI Label server in this notebook and plan to close the notebook, ensure that you terminate the kernel first. Failing to do so might result in an issue where the port remains occupied from the previous session when you try to restart the server later. To prevent this, always terminate the kernel before closing the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using PYTHONPATH=/home/chyang/anaconda3/envs:\n",
      "\n",
      "[2024-07-17 10:48:47,502] [681014] [MainThread] [INFO] (__main__:285) - USING:: version = False\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: app = /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: studies = /home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: verbose = INFO\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: conf = [['models', 'lung_nodule_ct_detection']]\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: host = 0.0.0.0\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: port = 8000\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: uvicorn_app = monailabel.app:app\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: ssl_keyfile = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: ssl_certfile = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: ssl_keyfile_password = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: ssl_ca_certs = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: workers = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: limit_concurrency = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: access_log = False\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: root_path = \n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: log_level = info\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: log_config = None\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: dryrun = False\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:285) - USING:: action = start_server\n",
      "[2024-07-17 10:48:47,503] [681014] [MainThread] [INFO] (__main__:296) - \n",
      "Allow Origins: ['*']\n",
      "[2024-07-17 10:48:48,087] [681014] [MainThread] [INFO] (uvicorn.error:82) - Started server process [681014]\n",
      "[2024-07-17 10:48:48,087] [681014] [MainThread] [INFO] (uvicorn.error:48) - Waiting for application startup.\n",
      "App Init...\n",
      "[2024-07-17 10:48:48,087] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.app:37) - Initializing App from: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle; studies: /home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr; conf: {'models': 'lung_nodule_ct_detection'}\n",
      "[2024-07-17 10:48:48,100] [681014] [MainThread] [INFO] (monailabel.utils.others.class_utils:57) - Subclass for MONAILabelApp Found: <class 'main.MyApp'>\n",
      "[2024-07-17 10:48:51,134] [681014] [MainThread] [INFO] (monailabel.utils.others.generic:304) - +++ Adding Bundle from Zoo: lung_nodule_ct_detection => /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection\n",
      "[2024-07-17 10:48:51,134] [681014] [MainThread] [INFO] (monailabel.utils.others.generic:364) - +++ Using Bundle Models: ['lung_nodule_ct_detection']\n",
      "[2024-07-17 10:48:51,134] [681014] [MainThread] [INFO] (monailabel.interfaces.app:135) - Init Datastore for: /home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr\n",
      "[2024-07-17 10:48:51,135] [681014] [MainThread] [INFO] (monailabel.datastore.local:130) - Auto Reload: True; Extensions: ['*.nii.gz', '*.nii', '*.nrrd', '*.jpg', '*.png', '*.tif', '*.svs', '*.xml']\n",
      "[2024-07-17 10:48:51,140] [681014] [MainThread] [INFO] (monailabel.datastore.local:577) - Invalidate count: 0\n",
      "[2024-07-17 10:48:51,140] [681014] [MainThread] [INFO] (monailabel.datastore.local:151) - Start observing external modifications on datastore (AUTO RELOAD)\n",
      "[2024-07-17 10:48:51,734] [681014] [MainThread] [INFO] (main:74) - +++ Adding Inferer:: lung_nodule_ct_detection => <monailabel.tasks.infer.bundle.BundleInferTask object at 0x75894da6cb50>\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (main:89) - +++ Adding Trainer:: lung_nodule_ct_detection => <monailabel.tasks.train.bundle.BundleTrainTask object at 0x75894d959d00>\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (main:99) - Active Learning Strategies:: ['random', 'first']\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (monailabel.utils.sessions:51) - Session Path: /home/chyang/.cache/monailabel/sessions\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (monailabel.utils.sessions:52) - Session Expiry (max): 3600\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (monailabel.interfaces.app:469) - App Init - completed\n",
      "[2024-07-17 10:48:51,735] [timeloop] [INFO] Starting Timeloop..\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (timeloop:60) - Starting Timeloop..\n",
      "[2024-07-17 10:48:51,735] [timeloop] [INFO] Registered job <function MONAILabelApp.on_init_complete.<locals>.run_scheduler at 0x75894d5a5670>\n",
      "[2024-07-17 10:48:51,735] [681014] [MainThread] [INFO] (timeloop:42) - Registered job <function MONAILabelApp.on_init_complete.<locals>.run_scheduler at 0x75894d5a5670>\n",
      "[2024-07-17 10:48:51,736] [timeloop] [INFO] Timeloop now started. Jobs will run based on the interval set\n",
      "[2024-07-17 10:48:51,736] [681014] [MainThread] [INFO] (timeloop:63) - Timeloop now started. Jobs will run based on the interval set\n",
      "[2024-07-17 10:48:51,736] [681014] [MainThread] [INFO] (uvicorn.error:62) - Application startup complete.\n",
      "[2024-07-17 10:48:51,736] [681014] [MainThread] [INFO] (uvicorn.error:214) - Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)\n",
      "[2024-07-17 10:49:12,353] [681014] [MainThread] [INFO] (monailabel.endpoints.activelearning:44) - Active Learning Request: {'strategy': 'random', 'client_id': 'user-xyz'}\n",
      "[2024-07-17 10:49:12,355] [681014] [MainThread] [INFO] (monailabel.tasks.activelearning.random:47) - Random: Selected Image: lung_054; Weight: 1721184552\n",
      "[2024-07-17 10:49:12,359] [681014] [MainThread] [INFO] (monailabel.endpoints.activelearning:60) - Next sample: {'id': 'lung_054', 'weight': 1721184552, 'path': '/home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr/lung_054.nii.gz', 'ts': 1721184095, 'name': 'lung_054.nii.gz'}\n",
      "[2024-07-17 10:49:17,159] [681014] [MainThread] [INFO] (monailabel.endpoints.infer:171) - Infer Request: {'model': 'lung_nodule_ct_detection', 'image': 'lung_054', 'device': 'NVIDIA GeForce RTX 3080 Ti', 'model_filename': 'model.pt', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz'}\n",
      "[2024-07-17 10:49:17,160] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:280) - Infer Request (final): {'device': 'cuda', 'model_filename': 'model.pt', 'model': 'lung_nodule_ct_detection', 'image': '/home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr/lung_054.nii.gz', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz', 'description': 'A pre-trained model for volumetric (3D) detection of the lung lesion from CT image on LUNA16 dataset'}\n",
      "[2024-07-17 10:49:17,169] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:76) - PRE - Run Transform(s)\n",
      "[2024-07-17 10:49:17,169] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:77) - PRE - Input Keys: ['device', 'model_filename', 'model', 'image', 'result_extension', 'result_dtype', 'client_id', 'description', 'image_path']\n",
      "[2024-07-17 10:49:18,662] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (LoadImageTensord): Time: 1.4925; image: torch.Size([512, 512, 241])(torch.float32)\n",
      "[2024-07-17 10:49:18,663] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureChannelFirstd): Time: 0.0003; image: torch.Size([1, 512, 512, 241])(torch.float32)\n",
      "[2024-07-17 10:49:18,684] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (Orientationd): Time: 0.0216; image: torch.Size([1, 512, 512, 241])(torch.float32)\n",
      "[2024-07-17 10:49:18,828] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (ScaleIntensityRanged): Time: 0.1437; image: torch.Size([1, 512, 512, 241])(torch.float32)\n",
      "[2024-07-17 10:49:18,829] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureTyped): Time: 0.0001; image: torch.Size([1, 512, 512, 241])(torch.float32)\n",
      "[2024-07-17 10:49:18,980] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:556) - Detector Inferer:: cuda => SlidingWindowInferer => {'roi_size': [512, 512, 192], 'sw_batch_size': 1, 'overlap': 0.25, 'mode': constant, 'sigma_scale': 0.125, 'padding_mode': constant, 'cval': 0.0, 'sw_device': None, 'device': 'cpu', 'progress': False, 'cpu_thresh': None, 'buffer_steps': None, 'buffer_dim': -1, 'with_coord': False, 'roi_weight_map': None}\n",
      "[2024-07-17 10:49:18,980] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:432) - Infer model path: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 10:49:18,980] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:440) - Using <User> provided model_file: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 10:49:19,111] [681014] [MainThread] [ERROR] (uvicorn.error:412) - Exception in ASGI application\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py\", line 407, in run_asgi\n",
      "    result = await app(  # type: ignore[func-returns-value]\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py\", line 69, in __call__\n",
      "    return await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/applications.py\", line 1054, in __call__\n",
      "    await super().__call__(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/applications.py\", line 123, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 186, in __call__\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 164, in __call__\n",
      "    await self.app(scope, receive, _send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/cors.py\", line 85, in __call__\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/exceptions.py\", line 65, in __call__\n",
      "    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 756, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 776, in app\n",
      "    await route.handle(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 297, in handle\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 77, in app\n",
      "    await wrap_app_handling_exceptions(app, request)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 72, in app\n",
      "    response = await func(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 278, in app\n",
      "    raw_response = await run_endpoint_function(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 191, in run_endpoint_function\n",
      "    return await dependant.call(**values)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 206, in api_run_inference\n",
      "    return run_inference(background_tasks, model, image, session_id, params, file, label, output)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 172, in run_inference\n",
      "    result = instance.infer(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/interfaces/app.py\", line 307, in infer\n",
      "    result_file_name, result_json = task(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 305, in __call__\n",
      "    data = self.run_detector(data, device=device)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 576, in run_detector\n",
      "    outputs = detector(inputs, use_inferer=True)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_detector.py\", line 524, in forward\n",
      "    head_outputs = predict_with_inferer(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 136, in predict_with_inferer\n",
      "    head_outputs_sequence = inferer(images, _network_sequence_output, network, keys=keys)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/inferer.py\", line 515, in __call__\n",
      "    return sliding_window_inference(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/utils.py\", line 229, in sliding_window_inference\n",
      "    seg_prob_out = predictor(win_data, *args, **kwargs)  # batched patch\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 75, in _network_sequence_output\n",
      "    head_outputs = network(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_network.py\", line 330, in forward\n",
      "    features = self.feature_extractor(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/networks/blocks/backbone_fpn_utils.py\", line 133, in forward\n",
      "    x = self.body(x)  # backbone\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torchvision/models/_utils.py\", line 69, in forward\n",
      "    x = module(x)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 610, in forward\n",
      "    return self._conv_forward(input, self.weight, self.bias)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 605, in _conv_forward\n",
      "    return F.conv3d(\n",
      "torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 3.00 GiB. GPU \n",
      "[2024-07-17 11:03:04,995] [681014] [MainThread] [INFO] (monailabel.endpoints.activelearning:44) - Active Learning Request: {'strategy': 'random', 'client_id': 'user-xyz'}\n",
      "[2024-07-17 11:03:04,997] [681014] [MainThread] [INFO] (monailabel.tasks.activelearning.random:47) - Random: Selected Image: lung_057; Weight: 1721185384\n",
      "[2024-07-17 11:03:05,001] [681014] [MainThread] [INFO] (monailabel.endpoints.activelearning:60) - Next sample: {'id': 'lung_057', 'weight': 1721185384, 'path': '/home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr/lung_057.nii.gz', 'ts': 1721184095, 'name': 'lung_057.nii.gz'}\n",
      "[2024-07-17 11:03:22,590] [681014] [MainThread] [INFO] (monailabel.endpoints.infer:171) - Infer Request: {'model': 'lung_nodule_ct_detection', 'image': 'lung_057', 'device': 'NVIDIA GeForce RTX 3080 Ti', 'model_filename': 'model.pt', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz'}\n",
      "[2024-07-17 11:03:22,591] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:280) - Infer Request (final): {'device': 'cuda', 'model_filename': 'model.pt', 'model': 'lung_nodule_ct_detection', 'image': '/home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr/lung_057.nii.gz', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz', 'description': 'A pre-trained model for volumetric (3D) detection of the lung lesion from CT image on LUNA16 dataset'}\n",
      "[2024-07-17 11:03:22,599] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:76) - PRE - Run Transform(s)\n",
      "[2024-07-17 11:03:22,599] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:77) - PRE - Input Keys: ['device', 'model_filename', 'model', 'image', 'result_extension', 'result_dtype', 'client_id', 'description', 'image_path']\n",
      "[2024-07-17 11:03:23,283] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (LoadImageTensord): Time: 0.6832; image: torch.Size([512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:03:23,283] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureChannelFirstd): Time: 0.0001; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:03:23,294] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (Orientationd): Time: 0.0103; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:03:23,359] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (ScaleIntensityRanged): Time: 0.065; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:03:23,359] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureTyped): Time: 0.0001; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:03:23,361] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:556) - Detector Inferer:: cuda => SlidingWindowInferer => {'roi_size': [512, 512, 192], 'sw_batch_size': 1, 'overlap': 0.25, 'mode': constant, 'sigma_scale': 0.125, 'padding_mode': constant, 'cval': 0.0, 'sw_device': None, 'device': 'cpu', 'progress': False, 'cpu_thresh': None, 'buffer_steps': None, 'buffer_dim': -1, 'with_coord': False, 'roi_weight_map': None}\n",
      "[2024-07-17 11:03:23,361] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:432) - Infer model path: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 11:03:23,361] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:440) - Using <User> provided model_file: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 11:03:23,429] [681014] [MainThread] [ERROR] (uvicorn.error:412) - Exception in ASGI application\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py\", line 407, in run_asgi\n",
      "    result = await app(  # type: ignore[func-returns-value]\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py\", line 69, in __call__\n",
      "    return await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/applications.py\", line 1054, in __call__\n",
      "    await super().__call__(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/applications.py\", line 123, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 186, in __call__\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 164, in __call__\n",
      "    await self.app(scope, receive, _send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/cors.py\", line 85, in __call__\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/exceptions.py\", line 65, in __call__\n",
      "    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 756, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 776, in app\n",
      "    await route.handle(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 297, in handle\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 77, in app\n",
      "    await wrap_app_handling_exceptions(app, request)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 72, in app\n",
      "    response = await func(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 278, in app\n",
      "    raw_response = await run_endpoint_function(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 191, in run_endpoint_function\n",
      "    return await dependant.call(**values)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 206, in api_run_inference\n",
      "    return run_inference(background_tasks, model, image, session_id, params, file, label, output)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 172, in run_inference\n",
      "    result = instance.infer(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/interfaces/app.py\", line 307, in infer\n",
      "    result_file_name, result_json = task(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 305, in __call__\n",
      "    data = self.run_detector(data, device=device)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 576, in run_detector\n",
      "    outputs = detector(inputs, use_inferer=True)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_detector.py\", line 524, in forward\n",
      "    head_outputs = predict_with_inferer(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 136, in predict_with_inferer\n",
      "    head_outputs_sequence = inferer(images, _network_sequence_output, network, keys=keys)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/inferer.py\", line 515, in __call__\n",
      "    return sliding_window_inference(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/utils.py\", line 229, in sliding_window_inference\n",
      "    seg_prob_out = predictor(win_data, *args, **kwargs)  # batched patch\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 75, in _network_sequence_output\n",
      "    head_outputs = network(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_network.py\", line 330, in forward\n",
      "    features = self.feature_extractor(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/networks/blocks/backbone_fpn_utils.py\", line 133, in forward\n",
      "    x = self.body(x)  # backbone\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torchvision/models/_utils.py\", line 69, in forward\n",
      "    x = module(x)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 610, in forward\n",
      "    return self._conv_forward(input, self.weight, self.bias)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 605, in _conv_forward\n",
      "    return F.conv3d(\n",
      "torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 3.00 GiB. GPU \n",
      "[2024-07-17 11:32:45,320] [681014] [MainThread] [INFO] (monailabel.endpoints.infer:171) - Infer Request: {'model': 'lung_nodule_ct_detection', 'image': 'lung_057', 'device': 'NVIDIA GeForce RTX 3080 Ti', 'model_filename': 'model.pt', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz'}\n",
      "[2024-07-17 11:32:45,321] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:280) - Infer Request (final): {'device': 'cuda', 'model_filename': 'model.pt', 'model': 'lung_nodule_ct_detection', 'image': '/home/chyang/Documents/monai_tutorials_gitee/monailabel/datasets/Task06_Lung/imagesTr/lung_057.nii.gz', 'result_extension': '.nrrd', 'result_dtype': 'uint8', 'client_id': 'user-xyz', 'description': 'A pre-trained model for volumetric (3D) detection of the lung lesion from CT image on LUNA16 dataset'}\n",
      "[2024-07-17 11:32:45,328] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:76) - PRE - Run Transform(s)\n",
      "[2024-07-17 11:32:45,328] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:77) - PRE - Input Keys: ['device', 'model_filename', 'model', 'image', 'result_extension', 'result_dtype', 'client_id', 'description', 'image_path']\n",
      "[2024-07-17 11:32:45,984] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (LoadImageTensord): Time: 0.6554; image: torch.Size([512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:32:45,984] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureChannelFirstd): Time: 0.0001; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:32:45,995] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (Orientationd): Time: 0.0101; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:32:46,069] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (ScaleIntensityRanged): Time: 0.0743; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:32:46,069] [681014] [MainThread] [INFO] (monailabel.interfaces.utils.transform:122) - PRE - Transform (EnsureTyped): Time: 0.0001; image: torch.Size([1, 512, 512, 112])(torch.float32)\n",
      "[2024-07-17 11:32:46,071] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:556) - Detector Inferer:: cuda => SlidingWindowInferer => {'roi_size': [512, 512, 192], 'sw_batch_size': 1, 'overlap': 0.25, 'mode': constant, 'sigma_scale': 0.125, 'padding_mode': constant, 'cval': 0.0, 'sw_device': None, 'device': 'cpu', 'progress': False, 'cpu_thresh': None, 'buffer_steps': None, 'buffer_dim': -1, 'with_coord': False, 'roi_weight_map': None}\n",
      "[2024-07-17 11:32:46,071] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:432) - Infer model path: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 11:32:46,071] [681014] [MainThread] [INFO] (monailabel.tasks.infer.basic_infer:440) - Using <User> provided model_file: /home/chyang/Documents/monai_tutorials_gitee/monailabel/apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt\n",
      "[2024-07-17 11:32:46,103] [681014] [MainThread] [ERROR] (uvicorn.error:412) - Exception in ASGI application\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py\", line 407, in run_asgi\n",
      "    result = await app(  # type: ignore[func-returns-value]\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py\", line 69, in __call__\n",
      "    return await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/applications.py\", line 1054, in __call__\n",
      "    await super().__call__(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/applications.py\", line 123, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 186, in __call__\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 164, in __call__\n",
      "    await self.app(scope, receive, _send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/cors.py\", line 85, in __call__\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/middleware/exceptions.py\", line 65, in __call__\n",
      "    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 756, in __call__\n",
      "    await self.middleware_stack(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 776, in app\n",
      "    await route.handle(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 297, in handle\n",
      "    await self.app(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 77, in app\n",
      "    await wrap_app_handling_exceptions(app, request)(scope, receive, send)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 64, in wrapped_app\n",
      "    raise exc\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/_exception_handler.py\", line 53, in wrapped_app\n",
      "    await app(scope, receive, sender)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/starlette/routing.py\", line 72, in app\n",
      "    response = await func(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 278, in app\n",
      "    raw_response = await run_endpoint_function(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/fastapi/routing.py\", line 191, in run_endpoint_function\n",
      "    return await dependant.call(**values)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 206, in api_run_inference\n",
      "    return run_inference(background_tasks, model, image, session_id, params, file, label, output)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/endpoints/infer.py\", line 172, in run_inference\n",
      "    result = instance.infer(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/interfaces/app.py\", line 307, in infer\n",
      "    result_file_name, result_json = task(request)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 305, in __call__\n",
      "    data = self.run_detector(data, device=device)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monailabel/tasks/infer/basic_infer.py\", line 576, in run_detector\n",
      "    outputs = detector(inputs, use_inferer=True)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_detector.py\", line 524, in forward\n",
      "    head_outputs = predict_with_inferer(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 136, in predict_with_inferer\n",
      "    head_outputs_sequence = inferer(images, _network_sequence_output, network, keys=keys)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/inferer.py\", line 515, in __call__\n",
      "    return sliding_window_inference(\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/inferers/utils.py\", line 229, in sliding_window_inference\n",
      "    seg_prob_out = predictor(win_data, *args, **kwargs)  # batched patch\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/utils/predict_utils.py\", line 75, in _network_sequence_output\n",
      "    head_outputs = network(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/apps/detection/networks/retinanet_network.py\", line 330, in forward\n",
      "    features = self.feature_extractor(images)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/monai/networks/blocks/backbone_fpn_utils.py\", line 133, in forward\n",
      "    x = self.body(x)  # backbone\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torchvision/models/_utils.py\", line 69, in forward\n",
      "    x = module(x)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1532, in _wrapped_call_impl\n",
      "    return self._call_impl(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1541, in _call_impl\n",
      "    return forward_call(*args, **kwargs)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 610, in forward\n",
      "    return self._conv_forward(input, self.weight, self.bias)\n",
      "  File \"/home/chyang/anaconda3/envs/monai/lib/python3.9/site-packages/torch/nn/modules/conv.py\", line 605, in _conv_forward\n",
      "    return F.conv3d(\n",
      "torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 3.00 GiB. GPU \n"
     ]
    }
   ],
   "source": [
    "!monailabel start_server --app apps/monaibundle --studies datasets/Task06_Lung/imagesTr --conf models lung_nodule_ct_detection"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 (Optional) Modify Detection Parameters in the Bundle\n",
    "\n",
    "The lung_nodule_ct_detection bundle can set box prediction probability threshold. In `apps/monaibundle/model/lung_nodule_ct_detection_v0.5.0/configs/inference.json`, it's define here `score_thresh=0.02`: \n",
    "\n",
    "```json\n",
    "    \"detector_ops\": [\n",
    "        \"$@detector.set_target_keys(box_key='box', label_key='label')\",\n",
    "        \"$@detector.set_box_selector_parameters(score_thresh=0.02,topk_candidates_per_level=1000,nms_thresh=0.22,detections_per_img=300)\",\n",
    "        \"$@detector.set_sliding_window_inferer(roi_size=@infer_patch_size,overlap=0.25,sw_batch_size=1,mode='constant',device='cpu')\"\n",
    "    ],\n",
    "\n",
    "```\n",
    "\n",
    "This parameter will impact the number of boxes in the final prediction output. Then show all boxes ROIs in 3D Slicer.\n",
    "\n",
    "If users want to limit the number of predicted boxes showing on 3D Slicer, users can set higher `score_thresh`, e.g., `score_thresh=0.5`, `score_thresh=0.6`, or even higher. "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Auto Box Detection with 3D Slicer\n",
    "\n",
    "Below is a step-by-step tutorial on using 3D Slicer for auto lung nodule detection. Pre-trained model is provided by the bundle and loaded by MONAI Label server.\n",
    "\n",
    "\n",
    "**Start 3D Slicer and MONAI Label Plugin**: the tutorial starts with monaibundle app in the 3D Slicer, please refer to the [\"Hello World\" tutorial](monailabel_HelloWorld_radiology_3dslicer.ipynb) for detailed instructions on installing 3D Slicer and MONAI Label plugin.\n",
    "\n",
    "**Important**: If your MONAI Label plugin is from older release, please refer to [Prerequisites](#Prerequisites) in this notebook to update and use latest MONAI Label plugin. The detection task needs to draw ROI nodes to 3D Slicer markups.\n",
    "\n",
    "### 2.1 Select Model and Fetch Data\n",
    "\n",
    "- Select the bundle model loaded with MONAI Label server, **lung_nodule_ct_detection** in this tutorial. Start MONAI Label server will automatically download the bundle.\n",
    "\n",
    "\n",
    "click **next sample** to load image data from datastore.\n",
    "\n",
    "![slicer1](./figures/monailabel_detection_3dslicer/detection1.png)\n",
    "\n",
    "\n",
    "### 2.2 Run Auto Inference\n",
    "\n",
    "- MONAI Label has loaded the pre-trained weights within the bundle for multi-organ segmentation task, click **run** to do inference on the currently loaded data. \n",
    "\n",
    "- Note: the pre-trained models are in the bundle's \"**models**\" folder. For instance, in this usecase, a downloaded pre-trained model is saved at \"**apps/monaibundle/model/lung_nodule_ct_detection/models/model.pt**\".\n",
    "\n",
    "- Note: the detection model uses RetinaNet, please reserve at least ~12G memory for inference and training, modify the bundle config file if out of memory.\n",
    "- Users can move the axis and slices to view the correct location of segmentation.\n",
    "\n",
    "Users can monitor the logs in the MONAI Label server terminal\n",
    "\n",
    "![slicer1](./figures/monailabel_detection_3dslicer/detection2.png)\n",
    "\n",
    "\n",
    "### 2.3 Edit Annotations and Submit Label\n",
    "\n",
    "- Users can edit the inference labels manually using 3D Slicer ROI box Editor, click the **Markups** tab on the top, the tools for adjusting ROIs. Once done annotation, users can go back to MONAI Label plugin and click **Submit Label** to save the ground truth label to the file system.\n",
    "\n",
    "- Note: the final annotations will be saved to \"**labels/final**\" folder in the study dataset, for example, in this usecase, the ground truth label will be saved to \"**datasets/Task06_Lung/imagesTr/labels/final**\"\n",
    "\n",
    "- The saved annotation will be in JSON file with the 3D Slicer ROINode format. It can be loaded with 3D Slicer.\n",
    "\n",
    "![slicer1](./figures/monailabel_detection_3dslicer/detection3.png)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Active Learning with 3D Slicer\n",
    "\n",
    "Active learning and interactive fine-tuning models have highlighted features in MONAI Label, users can train their models anytime when new annotated labels are saved. Click **Train** button, MONAI Label server will fetch the saved final ground truth label and fine-tune the prior model. \n",
    "\n",
    "- Sample of annotated box coordinate in JSON file. \n",
    "\n",
    "![slicer1](./figures/monailabel_detection_3dslicer/detection4.png)\n",
    "\n",
    "\n",
    "Users can monitor the logs in the MONAI Label server terminal\n",
    "\n",
    "- The ROINode box annotation will be converted to the model-compatible ground truth label automatically.\n",
    "\n",
    "![slicer1](./figures/monailabel_detection_3dslicer/detection5.png)\n",
    "\n",
    "Same to the Radiology app, users can do auto segmentation using the latest fine-tuned model. \n",
    "The active learning process will select unlabeled batch data.\n",
    "\n",
    "The next image is selected, already trained images will be marked as labeled data, then won't be selected for the next labeling batch. Active learning strategies such as \"first/random\" will be used for selecting which unlabeled data to fetch. \n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Repeat Until All Data are Annotated and Trained \n",
    "\n",
    "Repeated fetch data and active learning process to section 2.2, until all unlabeled data are annotated and trained. \n",
    "\n",
    "For each training loop, the new best metric model will be saved in \"**model/model.pt**\", in this usecase, \"**apps/monaibundle/lung_nodule_ct_detection/model/model.pt**\" is saved."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Conclusion\n",
    "\n",
    "This tutorial demonstrates MONAI Label usage with monaibundle app, the lung nodule ct detection task is introduced. Active learning process, auto inference, detection editor, submit labels, and save models are included with the bundle. The monaibundle app highlights the robust model deployment for MONAI Label."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  },
  "vscode": {
   "interpreter": {
    "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
